package com.jfs.observer.request.impl;

import com.jfs.enums.SipMethodEnum;
import com.jfs.observer.SIPProcessorObserver;
import com.jfs.observer.request.SIPRequestProcessor;
import com.jfs.observer.request.abstracts.AbstractProcessor;
import com.jfs.properties.SipProperties;
import com.jfs.strategy.message.MessageStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.sip.RequestEvent;
import javax.sip.SipFactory;
import javax.sip.SipProvider;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description 请求方法为MESSAGE类型处理器
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022-08-23
 */
@Component
@Slf4j
public class SIPRequestMessageProcessor extends AbstractProcessor implements SIPRequestProcessor, InitializingBean {
    private final SIPProcessorObserver sipProcessorObserver;
    private final List<MessageStrategy> messageStrategies;

    public SIPRequestMessageProcessor(SipFactory sipFactory,
                                      SipProperties sipProperties,
                                      @Qualifier("tcpSipProvider") SipProvider tcpSipProvider,
                                      @Qualifier("udpSipProvider") SipProvider udpSipProvider,
                                      List<MessageStrategy> messageStrategies,
                                      SIPProcessorObserver sipProcessorObserver) {
        super(sipFactory, tcpSipProvider, udpSipProvider, sipProperties);
        this.messageStrategies = messageStrategies;
        this.sipProcessorObserver = sipProcessorObserver;
    }

    @Override
    @Async
    public void doProcess(RequestEvent requestEvent) {
        try {
            byte[] rawContent = requestEvent.getRequest().getRawContent();
            String content = new String(rawContent, StandardCharsets.UTF_8);
            for (MessageStrategy messageStrategy : messageStrategies
            ) {
                if (messageStrategy.support(content)) {
                    messageStrategy.processor(content, this, requestEvent);
                }
            }
        } catch (Exception e) {
            log.error("处理message请求发生异常:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        sipProcessorObserver.addRequestProcess(SipMethodEnum.MESSAGE, this);
    }
}
